<?php

/**
 * @author      :   QuangLT
 * @name        :   Thethao_Category
 * @copyright   :   Fpt Online
 * @todo        :   CAte model
 */
class Category {

    protected static $_instance = null;
    protected $_menu;
    protected $_section;
    protected $_cate = null;

    const CATE_DETAIL = 'cate_detail';
    const CATE_FULL = 'cate_full';

    /**
     * Constructor of class
     * we don't permit an explicit call of the constructor! (like $v = new Singleton())
     */
    protected function __construct() {
        
    }

    /**
     * Get singletom instance
     * @return Category
     */
    public final static function getInstance() {
        //Check instance
        if (is_null(self::$_instance)) {
            self::$_instance = new self();
        }

        //Return instance
        return self::$_instance;
    }

    /**
     * Get cate with detail by parent id
     * @param type $arrParams 
     */
    public function getCategoryByParentID($intParentCateID) {
        $arrCateDetail = array();
        try {
            $arrListCateID = $this->getListCateIdOfParent($intParentCateID);
            if (!empty($arrListCateID)) {
                // Get category infor from category id
                foreach ($arrListCateID as $intCatID) {
                    $arrCateDetail[] = $this->getDetailbyCateId($intCatID);
                }
            }
        } catch (Exception $ex) {
            //log error
            Fpt_Log::sendlog(4, $ex->getCode(), $ex->getMessage(), $ex->getTraceAsString(), null, null);
        }
        return $arrCateDetail;
    }

    /**
     * Get article by category code
     * @param string $strCode
     * @return <array> Article information 
     * @author: phongtx@fpt.net
     */
    public function getCategoryByCode($strCode) {
        try {
            $cateID = $this->getIdByCode($strCode);
            if ($cateID > 0) {
                $arrInfo = $this->getDetailbyCateId($cateID);
                return $arrInfo;
            }
        } catch (Exception $ex) {
            Fpt_Log::sendlog(4, $ex->getCode(), $ex->getMessage(), $ex->getTraceAsString(), null, null);
        }
        return false;
    }

    /**
     * Get category by category category id
     * @param string $strCode
     * @return <array> category information 
     * @author: nhanva@fpt.net
     */
    public function getCategoryByID($intCategoryID) {
        try 
        {
            $arrCatInfo = array();
            $this->getFullCategoryByParentID();
            $arrCatInfo = array_key_exists($intCategoryID, $this->_cate) ? $this->_cate[$intCategoryID] : array();
            
        } catch (Exception $ex) {
            Fpt_Log::sendlog(4, $ex->getCode(), $ex->getMessage(), $ex->getTraceAsString(), null, null);
        }
        // Return category info
        return $arrCatInfo;
    }

   
    public function getMenu($section = null) {
        if ($this->_menu == null) {
            $this->_cate = null;
            $this->getFullCategoryByParentID();
        }
        if ($section != null) {
            return $this->_menu["$section"];
        }
        return $this->_menu;
    }

    public function getListCateIdOfParent($cate_parent) {
        $this->getFullCategoryByParentID();
        if (array_key_exists($cate_parent, $this->_cate)) {
            return $this->_cate["$cate_parent"]['child'];
        }
        return array();
    }

    public function getIdByCode($strCode) {
        $this->getFullCategoryByParentID();
        foreach ($this->_cate as $row) {
            if ($strCode == $row['catecode']) {
                return $row['category_id'];
            }
        }
        return 0;
    }

    public function getDetailbyCateId($intId) {
        $this->getFullCategoryByParentID();
        return array_key_exists($intId, $this->_cate) ? $this->_cate[$intId] : array();
    }

    public function getCodeParent($intId) {
        $this->getFullCategoryByParentID();
        return array_key_exists($intId, $this->_cate) ? $this->_cate[$intId]['catecode'] : '';
    }

    /**
     * Get full category include all sub category
     * @param array $intCategoryID
     * @return array
     * @author nhanva@fpt.net
     */
    public function getFullCategoryByParentID() {
        if ($this->_cate == null) {
            $intCategoryID = SITE_ID;
            // Get instance memcache
            $memcacheInstance = Fpt_Global::getMemcacheInstance($intCategoryID);
            $keyCache = Fpt_Global::makeCacheKey(self::CATE_FULL, $intCategoryID);

            // Get full category from Memcache
            $arrFullCatInfo = $memcacheInstance->read($keyCache);
            //$arrFullCatInfo = array();
            // Data not in cache
            if (empty($arrFullCatInfo)) {
                // Get application config
                $config = Fpt_Global::getApplicationIni();

                // Get instance mysql
                $cateMysql = Fpt_Business_Category::getInstance($config['database']['default']);

                // Get cate in DB
                $arrFullCatInfo = $cateMysql->getFullCategoryByParentID($intCategoryID);

                if (!empty($arrFullCatInfo)) {

                    // Store category info to cache
                    $result = $memcacheInstance->write($keyCache, $arrFullCatInfo);

                    if ($result === false) {
                        Fpt_Log::sendlog(4, -1, 'memcache cate full', $intCategoryID, null, null);
                    }
                }
            }
            $arrFullCatInfo = array_reverse($arrFullCatInfo);
            foreach ($arrFullCatInfo as $value) {
                $p = $value['parent_id'];
                $c = $value['category_id'];
                $value['full_parent'] = explode(',', $value['full_parent']);
                $arrCate[$c] = $value;
                if (isset($arrTemp[$c])) {
                    $arrCate[$c]['child'] = $arrChild = array_keys($arrTemp[$c]);
                    foreach ($arrCate[$c]['child'] as $row) {
                        $arrChild = array_merge($arrChild, $arrCate[$row]['child']);
                    }
                    $arrCate[$c]['child'] = $arrChild;

                    $value['child'] = $arrTemp[$c];
                    unset($arrTemp[$c]);
                } else {
                    $arrCate[$c]['child'] = array();
                }
                $arrTemp[$p][$c] = $value;
            }
            $this->_menu = $arrTemp[SITE_ID];
            $this->_cate = $arrCate;
        }
        return $this->_cate;
    }

    /**
     * BACKEND: edit category => clear cache cate, dont' del data
     * @param int $cateID
     * @return type 
     */
    public function editCategory($cateID) {
        try {
            $intCategoryID = SITE_ID;

            //get key cache
            $keyCache = Fpt_Global::makeCacheKey(self::CATE_FULL, $intCategoryID);

            //Delete 1 key cache full only
            $delCate = Fpt_Global::deleteMemcache($intCategoryID, $keyCache);
            //precaching
            $this->_cate = null;
            $this->getFullCategoryByParentID();
            return $delCate;
        } catch (Exception $ex) {
            //log error
            Fpt_Log::sendlog(4, $ex->getCode(), $ex->getMessage(), $ex->getTraceAsString(), null, null);
        }
    }

}

